#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import re as osRe
from time import sleep as osSleep
import random as osRandom  # 随机数
from os import system as osSystem  # 管道处理
from os import popen as osPopen  # 管道处理
import os as osOs  # 内置shell交互
import sys as osSys
import gol


class Tools:
    # def __init__(self):
        # gol.get("sAdb") = gol.get("sAdb")


    # 随机函数
    def getRandom(self, iMin, iMax):
        return osRandom.randint(iMin, iMax)


    # 延时
    def setSleep(self, iMin, iMax=999):
        iRandom = iMin
        if iMax != 999:
            iRandom = self.getRandom(iMin, iMax)
        osSleep(iRandom)


    # 取坐标
    def bounds(self, oInfo):
        """
        Returns:
            left_top_x, left_top_y, right_bottom_x, right_bottom_y
        """
        bounds = oInfo['visibleBounds'] or oInfo["bounds"]
        lx, ly, rx, ry = bounds['left'], bounds['top'], bounds['right'], bounds['bottom'] # yapf: disable
        return (lx, ly, rx, ry)


    # 点击的中心坐标
    def center(self, oInfo, offset=(0.5, 0.5)):
        """
        Args:
            offset: optional, (x_off, y_off)
                (0, 0) means left-top, (0.5, 0.5) means middle(Default)
        Return:
            center point (x, y)
        """
        lx, ly, rx, ry = self.bounds(oInfo)
        if offset is None:
            offset = (0.5, 0.5)  # default center
        xoff, yoff = offset
        width, height = rx - lx, ry - ly
        x = lx + width * xoff
        y = ly + height * yoff
        return (x, y)


    # 点击
    def tap(self, iX, iY):
        # print('%s shell input tap %d %d' % (gol.get("sAdb"), iX, iY))
        osPopen('%s shell input tap %d %d' % (gol.get("sAdb"), iX, iY))


    # 滑动
    def move(self, tupCoordinate):
        # print('len', len(tupCoordinate))
        if len(tupCoordinate):
            iStartX = tupCoordinate[0]
            iStartY = tupCoordinate[1]
            iEndX = tupCoordinate[2]
            iEndY = tupCoordinate[3]
            # print('%s shell input swipe %d %d %d %d' % (gol.get("sAdb"), iStartX, iStartY, iEndX, iEndY))
            osPopen('%s shell input swipe %d %d %d %d' % (gol.get("sAdb"), iStartX, iStartY, iEndX, iEndY))


    # 调用app
    def callApp(self, sVal):
        osPopen('%s shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER --activity-clear-task -n %s' % (gol.get("sAdb"), sVal))
        # osPopen('%s shell am start -D -S -n %s' % (gol.get("sAdb"), sVal))


    # 关闭app
    def closeApp(self, sVal):
        # print('%s shell am force-stop %s' % (gol.get("sAdb"), sVal))
        osPopen('%s shell am force-stop %s' % (gol.get("sAdb"), sVal))

    # 亮屏
    def toLight(self, sVal=224):
        osPopen('%s shell input keyevent %s' % (gol.get("sAdb"), sVal))

    # back
    def back(self, sVal=4):
        osPopen('%s shell input keyevent %s' % (gol.get("sAdb"), sVal))

    # 最高宽
    def vmSize(self):
        sVmSize = osPopen('%s shell wm size' % gol.get("sAdb")).read()
        aVmSize = osRe.search(r'(\d+)x(\d+)', sVmSize)
        return {'w': aVmSize.group(1), 'h': aVmSize.group(2)}

    def moveDirection(self, sType='upl'):
        reVal = []
        if sType == 'upl': # 长上滑
            reVal = [425, 800, 460, 400]
        elif sType == 'downl': # 长下滑
            reVal = [460, 800, 425, 1400]            
        elif sType == 'up': # 短上滑
            reVal = [425, 880, 460, 800]
        elif sType == 'down': # 短下滑
            reVal = [460, 800, 425, 880]
        elif sType == 'left': # 看小说点右边翻页
            reVal = [897, 1213, 400, 1210]
        return reVal


    # 视频上滑
    def swipeMoive(self, sType='up', iLen=80, tupRan=(3, 5)):
        tupMoveVal = self.moveDirection(sType)
        i = 0
        while i < iLen:
            self.move(tupMoveVal)
            iRan = self.getRandom(tupRan[0], tupRan[1])
            i += iRan
            print('执行次数：%d, 时长：%d' % (i, iRan))  # 打印
            self.setSleep(iMin=iRan)  # 延时


    # 取 devices 列表 
    # 返回 ['192.168.10.176:5555', '192.168.10.191:5555']
    def getDeviceid(self):
        sInit = ''
        aAllInfo = osPopen('adb devices').readlines()

        for i in range(len(aAllInfo)):
            sInit += aAllInfo[i]

        # 取换行和tab中间的值 osRe.S 使 . 匹配包括换行在内的所有字符
        aDevicesNames = osRe.findall('\n(.+?)\t', sInit, osRe.S)
        aDevicesNames = [orgItem for orgItem in aDevicesNames if len(orgItem) > 8]
        # print('devices', aDevicesNames)
        return aDevicesNames


    # 倒数
    def countDown(self, iStep, sType=None):
        if (sType):
            tupMoveVal = self.moveDirection(sType)
        iFill = iStep // 30
        iLen = iStep // iFill
        while iStep > 0:
            if (sType):
                self.move(tupMoveVal)
            print("\r", end="")
            print("进度: {0}".format(iStep), "▓"*iLen, end="")
            osSys.stdout.flush()
            osSleep(1)
            iStep -= 1
